<?php
/**
 * 生成验证码
 *
 * @author Dracowyn
 * @since 2023-11-15 11:49
 */

include_once('functions.php');
session_start();

$width = 80;
$height = 30;

// 定义大小
$result = imagecreatetruecolor($width, $height);

// 定义背景色
$bgColor = imagecolorallocate($result, 238, 238, 238);

// 设置背景色
imagefilledrectangle($result, 0, 0, $width, $height, $bgColor);

// 定义字体颜色
$fontColor = imagecolorallocate($result, 255, 0, 0);

// 生成四个随机字符
$code1 = randStr(1);
$code2 = randStr(1);
$code3 = randStr(1);
$code4 = randStr(1);

$currentDirectory = dirname(__FILE__);
$fontPath = $currentDirectory . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . 'OpenSans-Light.ttf';

// 把字符加入图片里
imagettftext($result, 16, mt_rand(-30, 30), 10, 26, $fontColor, $fontPath, $code1);
imagettftext($result, 16, mt_rand(-30, 30), 25, 26, $fontColor, $fontPath, $code2);
imagettftext($result, 16, mt_rand(-30, 30), 45, 26, $fontColor, $fontPath, $code3);
imagettftext($result, 16, mt_rand(-30, 30), 65, 26, $fontColor, $fontPath, $code4);

// 生成干扰点
for ($i = 0; $i < 100; $i++) {
	$pointColor = imagecolorallocate($result, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
	imagesetpixel($result, mt_rand(0, $width), mt_rand(0, $height), $pointColor);
}

// 生成干扰线
for ($i = 0; $i < 5; $i++) {
	$lineColor = imagecolorallocate($result, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
	imageline($result, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $lineColor);
}

// 把验证码存入session
$_SESSION['code'] = $code1 . $code2 . $code3 . $code4;

// 输出图片
header('Content-type: image/png');
imagepng($result);